import 'package:dio/dio.dart';
import 'package:fsharing/core/models/store_apply_query.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

class StoreApplyQueryModel extends ViewModel {
  final Api api;
  String _errorMessage;
  StoreApplyQuery _data;

  StoreApplyQueryModel(this.api) : super() {
    _initData();
  }

  String get errorMessage => _errorMessage;

  StoreApplyQuery get data => _data;

  set data(StoreApplyQuery value) {
    _data = value;
    notifyListeners();
  }

  Future<ViewState> _initData() async {
    viewState = ViewState.busy;
    try {
      _data = await api.storeApplyQuery(cancelToken);
      viewState = ViewState.success;
    } on DioError catch (e) {
      var message = e.message;
      // 这里忽略还没有申请店铺的错误，使后面的逻辑处理统一。
      if (message == '操作失败：null') {
        _data = StoreApplyQuery(null, null, null, null, null, null, null, null);
        viewState = ViewState.success;
      } else {
        _errorMessage = message;
        viewState = ViewState.error;
      }
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
